#include    "pneumo-relay.h"

//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
PneumoReley::PneumoReley(double work_volume, QObject *parent) : BrakeDevice(parent)
  , V_work(work_volume)
  , K1(0.0)
  , K2(0.0)
  , Q_work(0.0)
  , pBC(0.0)
  , pPM(0.0)
  , Qbc(0.0)
  , k1(1.0)
{

}

//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
PneumoReley::~PneumoReley()
{

}

//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
void PneumoReley::setWorkAirFlow(double flow)
{
    Q_work = flow;
}

//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
void PneumoReley::setBrakeCylPressure(double pBC)
{
    this->pBC = pBC;
}

//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
void PneumoReley::setPipelinePressure(double pPM)
{
    this->pPM = pPM;
}

//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
double PneumoReley::getWorkPressure() const
{
    return getY(0);
}

//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
double PneumoReley::getBrakeCylAirFlow() const
{
    return Qbc;
}

//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
void PneumoReley::ode_system(const state_vector_t &Y,
                             state_vector_t &dYdt,
                             double t)
{
    Q_UNUSED(t)
    Q_UNUSED(Y)

    dYdt[0] = Q_work / V_work;
}


//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
void PneumoReley::preStep(state_vector_t &Y, double t)
{
    Q_UNUSED(t)

    double s1 = cut(k1 * (Y[0] - pBC), -1.0, 1.0);

    double v1 = hs_p(s1);

    double v2 = hs_n(s1);

    Qbc = K1 * (pPM - pBC) * v1 - K2 * pBC * v2;
}

//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
void PneumoReley::load_config(CfgReader &cfg)
{
    QString secName = "Device";

    cfg.getDouble(secName, "K1", K1);
    cfg.getDouble(secName, "K2", K2);
    cfg.getDouble(secName, "WorkVolume", V_work);
    cfg.getDouble(secName, "k1", k1);
}
